import os
import re
import sys
import json
# 获取上级目录并添加到sys.path
from pathlib import Path
parent_dir = str(Path(__file__).resolve().parent.parent)
sys.path.append(parent_dir)
sys.path.append(r"E:\python-knowledge\6项目实战\AI工具\Ollama")
from OllamaAPI import OllamaAPI
import pandas
from index_tts.infer_batch import indextts_batch_generate


def check_empty(input_file,out_file):
    ollama_api = OllamaAPI(model_name="qwen3:8b")
    try:
        # 读取文件内容并过滤空白行
        with open(input_file, 'r', encoding='utf-8') as f:
            with open(out_file, 'w', encoding='utf-8') as fw:
                lines = f.readlines()
                # 过滤掉空白行（包括只有空格或制表符的行）
                non_empty_lines = [line for line in lines if line.strip()]
                for index,line in enumerate(non_empty_lines):
                    if "*" in line:
                        print("开始修改~~！~！！")
                        pre_text = non_empty_lines[index-1]+line+non_empty_lines[index+1]
                        prompt = """语句中存在违禁词被替换为*符号,请结合提供的原文推测出词语并替换回来。不要修改其他内容。
                        返回内容为标准格式：{text:(修改后的语句)}。\n
                        原文为：\n
                        %s
                        要修改语句如下： \n
                        %s\n
                        """%(pre_text,line)

                        options = {"temperature": 0.6, "top_p": 0.9}  # 可选参数
                        respone = ollama_api.generate_text(prompt, options)  # 调用API并获取生成的文本
                        result = respone.split("</think>")[-1]
                        try:
                            result.replace(" ","")
                            text = re.search("\{text:(.+)\}",result,re.DOTALL).group(1)
                        except:
                            print("failed : ",result)
                            fw.write(line)           # 处理失败，写入原文
                        else:
                            print(1,line)
                            print(2,text)
                            fw.write(text)             # 写入处理后的内容
                    else:
                        fw.write(line)

        
        print(f"成功处理文件，输出路径: {out_file}")
        return out_file

    except FileNotFoundError:
        print(f"错误: 文件 '{input_file}' 不存在")
        return None
    except Exception as e:
        print(f"错误: 处理文件时发生异常: {e}")
        return None
    

def recheck(filepath):
    ollama_api = OllamaAPI(model_name="qwen3:8b")  # 替换为你想要使用的模型名称

    with open(filepath, 'r', encoding='utf-8') as f:
        with open(filepath.replace(".txt","_recheck.txt"), 'w', encoding='utf-8') as fw:
            check_text = ""
            # 定义句末符号的正则表达式模式
            sentence_end_pattern = r'[。！？!?；;…\n]+'

            for t in f.readlines():
                check_text += t
                check_text += "\n"
                if len(check_text) > 300:

                    prompt = """修改段落中的错别字和用词错误,若文中存在*号请推测出词语进行替换。不要过分修改原文。
                    返回内容为标准格式：\n
                    {text:(修改后的段落)}。\n
                    段落如下： \n
                    %s\n
                    """%(t)

                    options = {"temperature": 0.6, "top_p": 0.8}  # 可选参数
                    respone = ollama_api.generate_text(prompt, options)  # 调用API并获取生成的文本
                    result = respone.split("</think>")[-1]
                    
                    #json_string = re.search("\{.+\}",result,re.DOTALL).group()  # AI保证不了格式标准
                    try:
                        result.replace(" ","")
                        text = re.search("\{text:(.+)\}",result,re.DOTALL).group(1)
                    except:
                        print(result)
                        fw.write(check_text)
                    else:
                        # print(text)
                        fw.write(text)
                    check_text = ""
    return  


def check_error_voice(xlsx_dir):

    indextts = indextts_batch_generate
    convert_list = os.listdir(xlsx_dir)
    seed_path = r'E:\txt\seed2.xlsx'
    sheet_name = 'sparktts'
    voice_dict = indextts.read_voice_data(seed_path,sheet_name)  # 读取音色库

    with open("./log.log","w+",encoding="utf-8") as flog:
        for file_name in convert_list:
            print(file_name)
            sheet_name = 'Sheet'
            xls_path = os.path.join(xlsx_dir,file_name)
            text_dict = indextts.read_text_data(xls_path,sheet_name)   # 读取文本excel
            for i,text_info in enumerate(text_dict):
                if text_info["seed"] not in voice_dict.keys():
                    flog.write("%s 章  ：  %d 行 ： %s 不存在 \n"%(file_name,i,text_info["seed"]))

if __name__ == "__main__":
    # 测试示例
    # input_file = r"E:\txt\网游之无限\网游之无限.txt"
    # out_file = r"E:\txt\网游之无限\网游之无限s.txt"
    # check_empty(input_file,out_file)

    # check_empty(r"E:\txt\网游之无限\网游之无限.txt",r"E:\txt\网游之无限\网游之无限1.txt")

    check_error_voice(r"f:\txt\网游之无限\网游之无限1")   #检查无法识别的角色名 
    pass